﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RayDen.Library.Core.Components;
using RayDen.Library.Core.Primitives;
using RayDen.Library.Data;
using RayDen.Library.Entity.Interface;
using RayDen.Library.Entity.Scene;
using RayDen.RayEngine.Samplers;

namespace Lt.Managers
{
    public class TextureManager : Singleton<TextureManager>
    {
        private OptimizedTextureAtlas atlas;
        private TextureSamplingManager samplingManager;
        private Dictionary<string, int> nameToIDMap;

        public TextureManager()
        {
            samplingManager = new TextureSamplingManager(TextureSamplingQuality.Linear);
            atlas = new OptimizedTextureAtlas();
            nameToIDMap = new Dictionary<string, int>();
        }

        public void LoadTexture(TextureInfo tx)
        {
            if (tx == null)
                return;
            if (!atlas.Contains(tx))
            {
                var id = atlas.AddTexture(tx);
                nameToIDMap.Add(tx.Name.ToLowerInvariant(), id);
            }
        }

        public ITexture GetByInfo(TextureInfo ti)
        {
            if (ti == null)
                return null;
            return atlas[nameToIDMap[ti.Name.ToLowerInvariant()]];
        }

        public void Sample(int id, float u, float v, out RgbSpectrum sample)
        {
            RgbSpectrumInfo ss;
            samplingManager.SampleTexture(u, v, atlas[id], out ss);
            sample = (RgbSpectrum) ss;
        }
    }
}
